package utils

import (
	"chatroom/common/message"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"net"
)

//这里将这些方法关联到结构体中
type Transfer struct {
	//分析它应该有哪些字段
	Conn net.Conn
	Buf [8096]byte //这时传输时，使用缓冲
}

func (t *Transfer)ReadPkg() (mes message.Message,err error) {
	fmt.Println("读取客户端发送的数据...")
	_, err = t.Conn.Read(t.Buf[:4])
	if err != nil {
		return 
	}

	var pkgLen uint32
	pkgLen = binary.BigEndian.Uint32(t.Buf[:4])
	n,err :=  t.Conn.Read(t.Buf[:pkgLen])
	if n !=int(pkgLen) || err != nil{
		return
	}

	n, err = t.Conn.Read(t.Buf[:pkgLen])
	if n != int(pkgLen) || err != nil {
		return
	}
	err = json.Unmarshal(t.Buf[:pkgLen],&mes)
	if err != nil {
		fmt.Println("json.unmarshal error = ",err)
		return
	}
	return
}

func (t *Transfer)WritePkg(data []byte)(err error)  {
	var pkgLen uint32
	pkgLen = uint32(len(data))
	binary.BigEndian.PutUint32(t.Buf[:4],pkgLen)
	n,err := t.Conn.Write(t.Buf[:4])
	if n != 4 || err != nil {
		fmt.Println("conn.Write(bytes) fail", err)
		return
	}
	n, err = t.Conn.Write(data)
	if n != int(pkgLen) || err != nil {
		fmt.Println("conn.Write(bytes) fail", err)
		return
	}
	return
}